package com.example.backblog.controller;

import com.example.backblog.util.COSClientUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@CrossOrigin
public class FileUploadController {
    @Value("${my.config.savePath}")
    private String filePath;
    @Value("${my.config.picture}")
    private String picturePrefix;

    // 图片上传接口
    @PostMapping("uploadFile")
    @ResponseBody
    public Map<String,String> uploadFile(HttpServletRequest request, @RequestParam("editormd-image-file") MultipartFile file) throws IOException {
        Map<String,String> jsonObject = new HashMap ();
        // 获取文件后缀
        String name = file.getOriginalFilename ();
        int index = name.lastIndexOf (".");
        String extension = "";
        if (index > 0) {
            extension = name.substring (index);
        }
//        if (!WhiteFile.isWhite (extension)) {
//            jsonObject.put ("success", "false");
//            return jsonObject;
//        }
        String fileName = System.currentTimeMillis () + extension;
        File path = new File (filePath);
        File basePath = new File (path.getAbsolutePath () + "/" + fileName);
        if (!path.isDirectory ()) {
            path.mkdir ();
        }
        String rootPath = picturePrefix;
        jsonObject.put ("url", rootPath + "/" + fileName);
        jsonObject.put ("success", "true");
        jsonObject.put ("message", "upload success!");
        file.transferTo (basePath);
        return jsonObject;
    }
    /**
     * 腾讯云COS上传
     *
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/cosUpload")
    public ResponseEntity cosUpload(MultipartFile file) throws Exception {
        String filePath = COSClientUtil.upload(file);
        return ResponseEntity.ok(filePath);
    }


}
